#include "keyfile.h"
#include "common.h"


int32_t ofp_key_file_open(GKeyFile **file, uint8_t *file_name)
{
    GError *err = NULL;

    *file = g_key_file_new();

    g_key_file_load_from_file(*file, file_name, G_KEY_FILE_KEEP_TRANSLATIONS|G_KEY_FILE_KEEP_COMMENTS, &err);
    if (err != NULL) {
        OFP_LOGE("ofp_key_file_open %s failed \n", file_name);
        g_error_free(err);
        err = NULL;
        g_key_file_free(*file);
        *file = NULL;
        return -1;
    }


    return 0;
}

void ofp_key_file_close(GKeyFile *file)
{
    if (file != NULL) {
        g_key_file_free(file);
        file = NULL;
    }
}

uint8_t* ofp_key_file_get_string(GKeyFile* file, const gchar* group_name, const gchar* key)
{
    uint8_t *key_value = NULL;
    GError *err = NULL;

    key_value = g_key_file_get_string(file, group_name, key, &err);
    if (err != NULL) {
        g_error_free(err);
        err = NULL;
        key_value = NULL;
        OFP_LOGE("ofp_key_file_get_string %s  %s failed \n", group_name, key);
    }

    return key_value;
}


uint32_t ofp_key_file_get_integer(GKeyFile* file, const gchar* group_name, const gchar* key)
{
    uint32_t key_value = 0;
    GError *err = NULL;

    key_value = g_key_file_get_integer(file, group_name, key, &err);
    if (err != NULL) {
        g_error_free(err);
        err = NULL;
        key_value = 0xffffffff; //表示异常值
        OFP_LOGE("g_key_file_get_string %s  %s failed \n", group_name, key);
    }

    return key_value;
}

int32_t ofp_key_file_set_and_save_integer(GKeyFile* file, char *file_name,
    const gchar* group_name, const gchar* key, int32_t value)
{
    GError *err = NULL;
    g_key_file_set_integer(file, group_name, key, value);
    g_key_file_save_to_file(file, file_name, &err);
    if (err != NULL) {
        OFP_LOGE("g_key_file_save_to_file %s %s  %s failed \n", file_name, group_name, key);
        g_error_free(err);
        err = NULL;
        return -1;
    }
    return 0;
}
int32_t ofp_key_file_set_and_save_string(GKeyFile* file, uint8_t *file_name,
    const gchar* group_name, const gchar* key, uint8_t *str)
{
    GError *err = NULL;
    g_key_file_set_string(file, group_name, key, str);
    g_key_file_save_to_file(file, file_name, &err);
    if (err != NULL) {
        OFP_LOGE("g_key_file_save_to_file %s %s  %s failed \n", file_name, group_name, key);
        g_error_free(err);
        err = NULL;
        return -1;
    }
    return 0;
}


